﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.media;
using System.IO;
using System.Configuration;
using System.Web.Configuration;

namespace idseefeld.com.images
{
    public class MediaEvents : ApplicationBase
    {
        private IDseefeldImagesConfig config;
        public MediaEvents()
        {
            config = new IDseefeldImagesConfig();
            if (config.MediaEventsEnabled)
            {
                Media.BeforeSave += new Media.SaveEventHandler(Media_BeforeSave);
                Media.AfterSave += new Media.SaveEventHandler(Media_AfterSave);
            }
        }

        void Media_BeforeSave(Media sender, umbraco.cms.businesslogic.SaveEventArgs e)
        {

            try
            {
                UmbracoImage umbImg = new UmbracoImage(sender);
                Property prop = sender.getProperty("originalUploadFile");
                string originalUploadFile = prop != null ? prop.Value.ToString() : "";
                if (originalUploadFile != ImageToolHelper.BuildOriganlName(umbImg.Src, umbImg.Extension))
                {
                    File.Delete(HttpContext.Current.Server.MapPath(originalUploadFile));
                    prop.Value = "";
                }
                if (String.IsNullOrEmpty(umbImg.Src) && !String.IsNullOrEmpty(originalUploadFile))
                {
                    prop.Value = "";
                    FileInfo fInfo = new FileInfo(HttpContext.Current.Server.MapPath(originalUploadFile));
                    DirectoryInfo mediaFolder = fInfo.Directory;
                    foreach (FileInfo f in mediaFolder.GetFiles())
                    {
                        if (!String.IsNullOrEmpty(f.Extension))
                            f.Delete();
                    }
                }
            }
            catch { }
        }

        void Media_AfterSave(Media sender, umbraco.cms.businesslogic.SaveEventArgs e)
        {
            if (config.DocumentTypes.Contains(sender.ContentType.Alias + ","))
            {
                try
                {
                    ImageTools tool = new ImageTools(sender, config);
                    tool.GenerateImages();
                }
                catch (Exception ex)
                {
                    Log.Add(LogTypes.Error, sender.Id, "after save media: " + ex.Message);
                }
            }
        }
    }
}